package com.yang.o2o.util;

import com.sun.xml.internal.bind.v2.TODO;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class ImageUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();
    private static String  basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    //private static String  PathUtil.getImgBasePath() = PathUtil.getImgBasePath();
    /**
     * 将CommonsMultipartFile转换成File*/
    public static File transferCommonsMultipartFile(CommonsMultipartFile cFile){
        File newFile = new File(cFile.getOriginalFilename());
        try {
            cFile.transferTo(newFile);
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return newFile;
    }
    /**
     * 处理缩略图，返回图片的相对路径
     * addr: 图片的存储路径
     * */
    public static String generateThumbnail(InputStream inputStream,String fileName, String addr){
        //得倒一个随机的名字作为真实的名字
        String realFileName = getRandomFileName();
        //获取文件的扩展名
        String extension = getFileExtension(fileName);
        //如果文件夹不存在就创建文件
        makeDirPath(addr);
        //相对路径
        String relativeAddr = addr + realFileName + extension;
        logger.debug("relativeAddr is " + relativeAddr);
        //创建文件
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("complete addr is " + PathUtil.getImgBasePath() + relativeAddr);
        try {
            Thumbnails.of(inputStream).size(200,200)
                   // .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath + "/timg.png")),0.5f)
//                  //TODO 这里取货水印有点问题暂时采用硬编码，有问题时请更改水印的绝对路径
                    .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File("C:\\Users\\yang\\Desktop\\o2o\\ssm\\src\\main\\resources\\timg.png")),0.5f)
                    .outputQuality(0.8f)
                    .toFile(dest);
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return relativeAddr;
    }


    /**
     * 当前的时间年月日秒+5位随机数*/
    public static String getRandomFileName(){
        //获取随机数
        int rannum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return  nowTimeStr + rannum;
    }

    /***
     * 获取文件扩展名*/
    public static String getFileExtension(String fileName){
        String originalFileName = fileName;
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }

    /**
     * 创建路径*/
    public static void  makeDirPath (String addr){
        String realFileParentPath = PathUtil.getImgBasePath() + addr;
        File dirPath = new File(realFileParentPath);
        if(!dirPath.exists()){
           dirPath.mkdirs();
        }
    }
    /**
     * 删除图片的方法*/
    public static void  deleteFileOrPath (String path){
//判断path是文件还是路径，是文件删除文件，是路径删除路劲下所有文件
        File fileOrPath = new File(PathUtil.getImgBasePath() + path);
        if(fileOrPath.exists()){
            if(fileOrPath.isDirectory()){
                File files[] = fileOrPath.listFiles();
                for(int i = 0; i < files.length; i++){
                    files[i].delete();
                }
            }
            fileOrPath.delete();
        }
    }

}
